# include <reg52.h>

sbit DQ = P1^0;
void delay_1820(unsigned int us)
{
    while(us--);
}

bit Init_DS18B20(void)
{
   
    bit x=0;
    DQ = 1;
    delay_1820(8);
    DQ = 0;
    delay_1820(80);
    DQ = 1;
    delay_1820(14);
    x = DQ;
    delay_1820(20);
    return ~x;
}

unsigned char ReadOneChar(void)
{
    unsigned char i,dat=0;
    for(i=8;i>0;i--)
    {
        DQ = 0;
        dat >>= 1;
        DQ = 1;
        delay_1820(1);
        if(DQ)  dat|= 0x80;
        delay_1820(4);
    }
    return(dat);
}

void WriteOneChar(unsigned char dat)
{
    unsigned char i;
    for(i=8;i>0;i--)
    {
        DQ = 0;
        DQ = dat&0x01;
        delay_1820(5);
        DQ =1;
        dat >>= 1;
    }
}

unsigned int ReadTemperature(void)
{
    unsigned char temp_l,temp_h;
    unsigned int temp=0;
    Init_DS18B20();
    WriteOneChar(0xCC);
    WriteOneChar(0x44);
    Init_DS18B20();
    WriteOneChar(0xCC);
    WriteOneChar(0xBE);
    temp_l=ReadOneChar();
    temp_h=ReadOneChar();
    temp = temp_h;
    temp = (temp<<8)+temp_l;
    return(temp);
}

